router.push不刷新(8种解决方案) |
您所在的位置:网站首页 › vue fullpath › router.push不刷新(8种解决方案) |
原文地址:vue this.$router.push 页面不刷新总结(8种解决方式----覆盖所有场景)_echo忘川的博客-CSDN博客_router.push页面不刷新 这其实是一个很常见的问题,当使用push的时候,会向 history 栈添加一个新的记录,这个时候,再次添加一个完全相同的路由的时候,就不会再次刷新了. 没有耐心的可以直接看第九种方式,绝绝子,适用所有场景. 解决办法有这么几种: 1. 添加activated函数。 activated(){ 在这里插入代码片 } 2. 通过路由监听的方法。将mounted下的方法函数放到watch路由下 // 不推荐、用户体验不好 watch: { '$route' (to, from) { // 路由发生变化页面刷新 this.$router.go(0); } }, // 该方法会多一次请求 watch: { '$route' (to, from) { // 在mounted函数执行的方法,放到该处 this.getTableData(); } }, 3. 使用VUE的v-if控制DOM 注意:this.$router.push使用的是query不是params export default { name: 'App', data() { return { msg: 'Welcome to Your Vue.js App', searchText:'', RouteState:true, } }, methods: { reload(){ this.RouteState = false; this.$nextTick(()=>{ this.RouteState = true; }); this.$router.push({ name: 'doclist', query: { keywords:this.searchText } }); }, } } 4. 使用beforeRouteUpdate beforeRouteUpdate (to, from, next) { this.lang = to.params.lang; this.setCode(); next(); } 5. 通过组件导航守卫来设置对应的meta 属性 beforeRouteEnter: (to, from, next) = > { // 写在当前组件 to.meta.keepAlive = false next() }, beforeRouteLeave: (to, from, next) = > { //写在前一个组件 to.meta.keepAlive = false next() } 正常以上几种方式就会有效,但是有的时候也会有一些特殊的情况: 6. 在router-view上添加 :key="$route.fullPath"属性即可。 1 7. 跟缓存keep-alive有关 //添加exclude和 :key="$route.fullPath" 8.window的addEventListener监听方式 // 检测浏览器路由改变页面不刷新问题,hash模式的工作原理是hashchange事件 window.addEventListener('hashchange', () => { let currentPath = window.location.hash.slice(1) if (this.$route.path !== currentPath) { this.$router.push(currentPath) } }, false) 9.添加date:new Date().getTime() tip: 一个贼狗的方式,只需要一行代码,而且适用各种场景 this.$router.push({ path: "/homePage/searchResult", query: { keywords: this.input, type: this.type, date:new Date().getTime() } }) ———————————————— |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |